﻿using UnityEngine;
using UnityEngine.EventSystems;

namespace Watermelon
{
    public class FloatingJoystick : Joystick
    {
        [SerializeField] Color backgroundActiveColor = Color.white;
        [SerializeField] Color backgroundDisableColor = Color.white;

        [SerializeField] Color handleActiveColor = Color.white;
        [SerializeField] Color handleDisableColor = Color.white;

        [Space]
        [SerializeField] GameObject pointerGameObject;

        private Vector2 defaultAnchoredPosition;

        private Animator tutorialAnimator;
        private bool isTutorialDisplayed;

        // Events
        public static OnJoystickTouchedCallback OnJoystickTouched;

        protected override void Start()
        {
            base.Start();

            isJoysticActive = false;
            isTutorialDisplayed = false;

            tutorialAnimator = GetComponent<Animator>();

            backgroundImage.color = backgroundDisableColor;
            handleImage.color = handleDisableColor;

            defaultAnchoredPosition = background.anchoredPosition;
        }

        public override void OnPointerDown(PointerEventData eventData)
        {
            if (!isTutorialDisplayed)
            {
                isTutorialDisplayed = true;

                Destroy(tutorialAnimator);
                Destroy(pointerGameObject);
            }

            background.anchoredPosition = ScreenPointToAnchoredPosition(eventData.position);

            backgroundImage.color = backgroundActiveColor;
            handleImage.color = handleActiveColor;

            isJoysticActive = true;

            OnJoystickTouched?.Invoke();

            base.OnPointerDown(eventData);
        }

        public override void OnPointerUp(PointerEventData eventData)
        {
            if (!isJoysticActive)
                return;

            isJoysticActive = false;

            base.OnPointerUp(eventData);
        }

        public void DisableJoystick()
        {
            ResetInput();

            gameObject.SetActive(false);
        }

        public void EnableJoystick()
        {
            ResetInput();

            gameObject.SetActive(true);
        }

        public void HideAndResetInput()
        {
            isJoysticActive = false;

            ResetInput();
        }

        public void MakeTransparent()
        {
            backgroundImage.color = Color.clear;
            handleImage.color = Color.clear;
        }

        public override void ResetInput()
        {
            base.ResetInput();

            backgroundImage.color = backgroundDisableColor;
            handleImage.color = handleDisableColor;

            background.anchoredPosition = defaultAnchoredPosition;
        }

        public delegate void OnJoystickTouchedCallback();
    }
}